package com.fll.common.container;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.List;

/**
 *
 * 容器Container的启动停止帮助类
 *
 * 在启动或停止时进行修饰
 *
 * @author fanlei
 * @version 1.0
 * @date 2019年01月25日
 */
@Slf4j
public class ContainerHelper {

    //整个容器集合运行状态
    private static volatile boolean running = true;

    //容器集合
    private static List<Container> cachedContainers;

    public ContainerHelper() {
    }

    public static void start(List<Container> containers) {
        cachedContainers = containers;
        startContainers();

        //添加一个钩子，在jvm关闭的时候进行容器关闭
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                synchronized(ContainerHelper.class) {
                    ContainerHelper.stopContainers();
                    ContainerHelper.running = false;
                    ContainerHelper.class.notify();
                }
            }
        });

        synchronized(ContainerHelper.class) {
            while(running) {
                try {
                    ContainerHelper.class.wait();
                } catch (Throwable hrowable) {
                    ;
                }
            }

        }
    }

    private static void startContainers() {
        Iterator it = cachedContainers.iterator();

        while(it.hasNext()) {
            Container container = (Container)it.next();
            log.info("starting container [{}]", container.getClass().getName());
            container.start();
            log.info("container [{}] started", container.getClass().getName());
        }



    }

    private static void stopContainers() {
        Iterator it = cachedContainers.iterator();

        while(it.hasNext()) {
            Container container = (Container)it.next();
            log.info("stopping container [{}]", container.getClass().getName());

            try {
                container.stop();
                log.info("container [{}] stopped", container.getClass().getName());
            } catch (Exception e) {
                log.warn("container stopped with error", e);
            }
        }

    }    
}
